package com.example.demo.web.config;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.example.demo.web.util.RabbitAckReceiver;

@Configuration
public class MessageListenerConfig {
	@Autowired
    private CachingConnectionFactory connectionFactory;
	
	@Autowired
	private RabbitAckReceiver rabbitReceiver;
	
	public static final String TOPIC_QUEUE_CLOUD = "tp.cloud";
    public static final String TOPIC_QUEUE_HBEAT = "tp.hbeat";
    
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }
    
	
	@Bean
    public SimpleMessageListenerContainer cloudMessageListenerContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setConcurrentConsumers(1);
        container.setMaxConcurrentConsumers(3);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); // RabbitMQ默认是自动确认，这里改为手动确认消息
        //设置一个队列
        container.setQueueNames(TOPIC_QUEUE_CLOUD);

        container.setMessageListener(rabbitReceiver);
 
        return container;
    }
	
	@Bean
    public SimpleMessageListenerContainer hbeatMessageListenerContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setConcurrentConsumers(1);
        container.setMaxConcurrentConsumers(1);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); // RabbitMQ默认是自动确认，这里改为手动确认消息
        //设置一个队列
        container.setQueueNames(TOPIC_QUEUE_HBEAT);

        container.setMessageListener(rabbitReceiver);
 
        return container;
    }
}
